package cmd

import (
	"flag"
	"fmt"
	"github.com/spf13/cobra"
	k8s "k8s.io/client-go/kubernetes"
	restclient "k8s.io/client-go/rest"

	"k8s.io/client-go/tools/clientcmd"
	"time"
)

var namespace string
var version bool

// RootCommand 返回组装好的根命令
func RootCommand() *cobra.Command {
	// 定义根命令
	rootCmd := cobra.Command{
		Use: "cmd-kubectl",
		Run: func(cmd *cobra.Command, args []string) {
			if version {
				restclient, err := createK8SClientBysa()
				if err != nil {
					fmt.Println("Err:", err)
					return
				}
				// 通过 ServerVersion 方法来获取版本号
				versionInfo, err := restclient.ServerVersion()
				if err != nil {
					fmt.Println("Err:", err)
					return
				}
				fmt.Println("Kubernetes Version:", versionInfo.String())
			}
		},
	}
	// 添加全局选项参数
	rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "", "namespace")

	// 显示版本的信息
	rootCmd.Flags().BoolVarP(&version, "version", "v", false, "kubernetes version")

	// 添加子命令
	addCommands(&rootCmd)
	return &rootCmd
}

// addCommands 组装子命令
func addCommands(rootCmd *cobra.Command) {
	// Namespace
	namespaceRootCmd.AddCommand(&namespaceGetCmd)

	// Pod
	podRootCmd.AddCommand(&podGetCmd)

	// Deployment
	deploymentRootCmd.AddCommand(&deploymentGetCmd)

	// Service
	serviceRootCmd.AddCommand(&serviceGetCmd)

	// 组装命令
	rootCmd.AddCommand(&namespaceRootCmd)
	rootCmd.AddCommand(&podRootCmd)
	rootCmd.AddCommand(&serviceRootCmd)
	rootCmd.AddCommand(&deploymentRootCmd)
}

// 使用kubeconfig文件的鉴权信息创建 Kubernetes 的连接客户端
func createK8SClient() (k8sClient *k8s.Clientset, err error) {
	kubeconfig := flag.String("kubeconfig", "./kubeconfig", "absolute path to the kubeconfig file")
	flag.Parse()
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	k8sClient, err = k8s.NewForConfig(config)
	return
}

// 使用ServiceAccount账号鉴权信息创建 Kubernetes 的连接客户端
func createK8SClientBysa() (k8sClient *k8s.Clientset, err error) {
	var (
		// K8SCertificateData 表示 Kubernetes 服务端证书
		K8SCertificateData = `-----BEGIN CERTIFICATE-----
MIIC/jCCAeagAwIBAgIBADANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDEwprdWJl
cm5ldGVzMB4XDTIyMDczMTAwMDgxNVoXDTMyMDcyODAwMDgxNVowFTETMBEGA1UE
AxMKa3ViZXJuZXRlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALHc
iFkv0HbZFNFNXu+S93eTlhD5NuRL4jqr2YrSWbe7B4NLCYEjJznael8i3X9bw53E
+IloCUkKiUiRwm52gbBBWx2snvd3/PvfOMWh0SHI1Le2jTg5SRlEEPvR6lhhL2Zc
B7oMZ7JIaW4G/uz+0o1yFUy0MfNPs0FGt+MhUbzR6VeQGDWDsCikDQDTMcwqn+Q2
BPPA3ZgIEhVWRC6IGdwJ2LevZY5aIgAHKMXf17nsjOOdO8Hqno7vCtTMdfhAvNli
XkN0hEiqCTanRdlkH/6w8Fi1bN0NbdA6VY+yzDCmymaqiHeVqsoTQecWU0pdBpzy
wngEFgSOUc8aZrutN1cCAwEAAaNZMFcwDgYDVR0PAQH/BAQDAgKkMA8GA1UdEwEB
/wQFMAMBAf8wHQYDVR0OBBYEFCwPpFbgRXwlb7hL9bdSGhFa4c1nMBUGA1UdEQQO
MAyCCmt1YmVybmV0ZXMwDQYJKoZIhvcNAQELBQADggEBAF93/6e+V7G+CLddPCBb
4TXzGqwkDHD7kyvHRJGjLZVBloGuQ7GMDl+dB85W5horNZ7t+2ZHnFEPWVu0pnJO
WcTBVuyw/Ogdv0P4b0VZYa1UBk67mfe1u/QzND675d1R/9CF95xArEiqajIJviHK
3z5vYYRyAIDyubxv4YLmazbmcgMKSF/fzbeTs4GlrJmq7Sz9dQJXJAmtaynkprf7
E5gBk7MdaqIwlQX8oSykqPdZddlHKrrIOElQ8SYKEDiedyu+8zUbGz6XI6d9x8Qx
Ok5EYQ9PS4SkCDlEoi/y6aIxNNX6zoc/7EGm19tzJpzwEYB3x4GrXTOsf1CInJIV
Jlk=
-----END CERTIFICATE-----`

		// APIServer 表示 Kubernetes API Server 地址
		APIServer = "https://k8s.yunlearn.org:6443"

		// token 表示 ServiceAccount learn-admin 的 Secret 对应的 Token
		token = `eyJhbGciOiJSUzI1NiIsImtpZCI6Im9ONXZYOWw1MlJ0dnN2bE5YczlEQzFuam9nWmJuM0djWkZmOHJpRDBqVkUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImxlYXJuLWFkbWluLXRva2VuLWNqbjVjIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImxlYXJuLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiYTllNzVjY2MtNmNlNS00MTU5LThiZTktOTliZmJjNTc4MmZhIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRlZmF1bHQ6bGVhcm4tYWRtaW4ifQ.Ggl0bU_6Esw89kibT6HTD0Jr1XGaYXmWT1WTeJIpsGZiH7THwhcp4b1R01ZS_mpIeDy8ywfY4_j6UxbfsbfVT09opOWqsdcu9fQsS5qV34J7D9GUF4YRfk1kaV5P_t4j9Ht0P1wBkCl3hiq1J_cCwUV9IC_-4fpjg_h4VjEmpoab3hpJ-gWHII7psqRD3EIyBPxuS1RGJBrIW5LOrhtTnJtzcTq4epI1LO39kqyjLFpIj_OVBn8GxeFE2kdJdJ9ROvwgUyiFwnd0p_Mywqp4rqzX40xpkN_QMB7bs2ZmQn9HhipR19JaJDcex1q0KJ_MFkUvDLm1rdbbai_d3m67jg`
		// timeout 表示超时时间
		timeout = 30
	)

	cfg := restclient.Config{}
	cfg.Host = APIServer
	cfg.CAData = []byte(K8SCertificateData)
	cfg.BearerToken = token
	cfg.Timeout = time.Second * time.Duration(timeout)
	k8sClient, err = k8s.NewForConfig(&cfg)
	return
	return
}
